<html>
<h1>Calculator</h1>
<p>by Jose Rodriguez Salinas</p>
<p>CS 143, Spring 2012</p>
Type an expression in the follwing box.
<form method="GET">
<input type="text" name="expr"><input type="submit" value="Calculate">
<?php
$eqn=$_GET['expr'];
$num=0;

preg_match('@^(([+-]*)(\d+)(?:\.\d+)?)( )*(([/+*-])([+-]*)(\d+)(?:\.\d+)?){0,}$@i',$eqn,$matches);
$num=sizeof($matches);
$var=0;
if($_GET['expr']=='')
	exit;
	
if ($num > 0)
{
	preg_match('@([a-zA-z]+)@',$eqn,$error_alpha);
	preg_match('@([+-]*)(\d)\/0@',$eqn,$error_zero);
	preg_match('@([+]+)([+]+)@',$eqn,$error_plus_sign);
	preg_match('@([-]+)([-]+)@',$eqn,$error_minus_sign);
	
	if(sizeof($error_plus_sign)>0 || sizeof($error_minus_sign)>0 || sizeof($error_alpha)>0)
	{
		echo "<h2>Result</h2>Invalid input expression ". $_GET['expr'] .".";
		exit;
	}
	
	if (sizeof($error_zero)>0)
	{
		echo "<h2>Result</h2>Invalid input expression ".$_GET['expr'] . ".";
		exit;
	}
eval("\$var=$matches[0] ;");
echo "<h2>Result</h2>".$_GET['expr'].'= '.$var;
}
else
echo "<h2>Result</h2>"."Invalid input expression ".$_GET['expr'] .".";
?>
</form>
</html>

